from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import AllowAny
from django.conf import settings
from django.core.cache import cache
import json
import logging
from rest_framework.generics import ListAPIView
from .models import NavCategory, Banner, CourseCategory
from .serializers import NavCategorySerializer, BannerSerializer, CourseCategoryListSerializer

# 获取日志记录器
logger = logging.getLogger('apps')

# Create your views here.

class NavCategoryListAPIView(APIView):
    """导航栏分类列表接口"""
    permission_classes = [AllowAny]  # 允许匿名访问
    
    def get(self, request):
        """获取导航栏分类列表"""
        try:
            # 只返回启用状态的分类
            queryset = NavCategory.objects.filter(is_active=True)
            serializer = NavCategorySerializer(queryset, many=True)
            
            logger.info(f"成功获取导航分类列表，共{len(serializer.data)}条记录")
            return Response({
                "code": 1,
                "message": "success",
                "data": serializer.data
            })
            
        except Exception as e:
            logger.error(f"获取导航分类失败: {str(e)}")
            return Response({
                "code": 0,
                "message": f"获取导航分类失败: {str(e)}",
                "data": []
            })

class BannerListAPIView(APIView):
    """轮播图广告列表接口"""
    permission_classes = [AllowAny]  # 允许匿名访问
    
    def get(self, request):
        """获取轮播图广告列表"""
        try:
            # 缓存key
            cache_key = 'luffy:banner:list'
            
            # # 1. 尝试从Redis获取缓存数据
            # cache_data = cache.get(cache_key)
            # if cache_data:
            #     # 如果有缓存，直接返回缓存数据
            #     logger.info("从Redis缓存获取轮播图数据")
            #     return Response({
            #         "code": 1,
            #         "message": "success from cache",  # 标记来自缓存
            #         "data": json.loads(cache_data)
            #     })
            
            # 2. 如果没有缓存，从数据库获取数据
            logger.info("Redis缓存未命中，从数据库获取轮播图数据")
            queryset = Banner.objects.filter(
                is_show=True,    # 只查询显示的广告
                is_deleted=False # 未删除的广告
            ).order_by(
                '-weight',       # 按权重降序
                '-created_time'  # 按创建时间降序
            )
            
            # 3. 序列化数据
            serializer = BannerSerializer(queryset, many=True)
            
            # 4. 将数据存入Redis缓存
            # 将序列化数据转为JSON字符串存储，避免pickle序列化问题
            cache.set(
                cache_key,
                json.dumps(serializer.data),
                settings.BANNER_CACHE_TIME  # 使用配置的缓存时间
            )
            logger.info(f"成功获取轮播图列表并更新缓存，共{len(serializer.data)}条记录")
            
            # 5. 返回数据
            return Response({
                "code": 1,
                "message": "success from database",  # 标记来自数据库
                "data": serializer.data
            })
            
        except Exception as e:
            logger.error(f"获取轮播图列表失败: {str(e)}")
            return Response({
                "code": 0,
                "message": f"获取轮播图列表失败: {str(e)}",
                "data": []
            })

class CourseCategoryListAPIView(APIView):
    """课程分类列表视图"""
    permission_classes = [AllowAny]

    def get(self, request):
        """获取课程分类列表"""
        try:
            # 尝试从缓存中获取数据
            cache_key = 'luffy:course:categories'
            categories = cache.get(cache_key)
            if categories:
                return Response({
                    "code": 1,
                    "message": "success from cache",
                    "data": json.loads(categories)
                })

            # 如果缓存中没有数据，从数据库获取
            queryset = CourseCategory.objects.filter(level=1)  # 只获取一级分类
            serializer = CourseCategoryListSerializer(queryset, many=True)
            
            # 将数据存入缓存，设置过期时间为1小时
            cache.set(cache_key, json.dumps(serializer.data), timeout=3600)
            
            logger.info(f"成功获取课程分类列表并更新缓存，共{len(serializer.data)}条记录")
            return Response({
                "code": 1,
                "message": "success from database",
                "data": serializer.data
            })
            
        except Exception as e:
            logger.error(f"获取课程分类列表失败: {str(e)}")
            return Response({
                "code": 0,
                "message": f"获取课程分类列表失败: {str(e)}",
                "data": []
            })
